const multer = require("multer")

const path = require("path")

/**
 * 格式化数据
 * @param {*} code 
 * @param {*} msg 
 * @param {*} data 
 * @returns {
        "code":code,
        "msg":msg,
        "data":data
    }
 */

module.exports.formatResponse = function(code, msg, data) {
    return {
        "code": code,
        "msg": msg,
        "data": data
    }
}


module.exports.processingData = function(data) {

    if (typeof data === "Array") {
        return data.map(item => {
            return item.dataValues
        })
    } else if (typeof data === "object") {
        let arr = []
        for (let item of data) {
            arr.push(item.dataValues)
        }
        return arr
    }

}

/**
 * 上传文件的引擎
 */

const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        // 存储位置
        cb(null, path.resolve(__dirname, "../public/static/uploads"));
    },
    filename: function(req, file, cb) {
        // 时间戳-6位随机字符.文件后缀
        const timeStamp = Date.now();
        const ramdomStr = Math.random().toString(36).slice(-6);
        const ext = path.extname(file.originalname);
        const filename = `${timeStamp}-${ramdomStr}${ext}`;
        cb(null, filename);
    },
});

const upload = multer({
    storage,
    limits: {
        fileSize: 2000 * 1024,
    },
    fileFilter(req, file, cb) {
        //验证文件后缀名
        const extname = path.extname(file.originalname);
        const whitelist = [".jpg", ".gif", ".png", ".jpeg", ".JPG", ".GIF", ".PNG", ".JPEG", ".WEBP", ".webp"];
        if (whitelist.includes(extname)) {
            cb(null, true);
        } else {
            cb(new Error(`your ext name of ${extname} is not support`));
        }
    },
});

module.exports.upload = upload